﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using OPLService.BusinessEntities;

namespace OPLService.DAL
{
    public class OPLDataAccess
    {
        OPLModelContext dbCntxt = new OPLModelContext();

        public List<NotificationDetails> GetNotifications(DateTime startDate)
        {
            
            List<NotificationDetails> res= (from notifctns in dbCntxt.Notifications
                                            where notifctns.NotifiedOn >= startDate
                select new NotificationDetails {Id= notifctns.Id,Caption= notifctns.Caption,Description= notifctns.Description,NotifiedOn= notifctns.NotifiedOn }).ToList() ;

            return res;
        }

        public Int32 AddNotifications(string notifyString)
        {
            Notification objNotification = new Notification();
             
            Int32 notifyId=0;


            if (dbCntxt.Notifications.FirstOrDefault() != null ) 
            { 
                notifyId = (from notification in dbCntxt.Notifications select notification.Id).Max(); 
            }

            notifyId = notifyId+1;
            objNotification.Id = notifyId;
            objNotification.Caption=notifyString;
            objNotification.Description = notifyString;
            objNotification.NotifiedOn = DateTime.UtcNow;
            dbCntxt.AddObject("Notifications",objNotification);
            dbCntxt.SaveChanges();
            return notifyId;
        }

        public List<NotificationDetails> GetLatestNotifications(int count, int lowerLimit)
        {
            List<NotificationDetails> res = (from notifctns in dbCntxt.Notifications
                                             where notifctns.Id > lowerLimit
                                             select new NotificationDetails { Id = notifctns.Id, Caption = notifctns.Caption, Description = notifctns.Description, NotifiedOn = notifctns.NotifiedOn })
                                             .OrderByDescending( x => x.Id).Take(count).ToList();

            return res;
        }
    }
}
